package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.domain.StreetCommunity;
import com.ruoyi.system.domain.SysAdministrative;
import com.ruoyi.system.service.ISysAdministrativeService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SubCommunity;
import com.ruoyi.system.service.ISubCommunityService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * sub_communityController
 * 
 * @author wfj
 * @date 2025-10-29
 */
@RestController
@RequestMapping("/system/subCommunity")
public class SubCommunityController extends BaseController
{
    @Autowired
    private ISubCommunityService subCommunityService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysAdministrativeService sysAdministrativeService;


    /**
     * 查询sub_community列表
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:list')")
    @GetMapping("/list")
    public TableDataInfo list(SubCommunity subCommunity)
    {
        startPage();
        List<SubCommunity> list = subCommunityService.selectSubCommunityList(subCommunity);
        return getDataTable(list);
    }

    /**
     * 查询sub_community列表
     */
    @GetMapping("/listAll")
    public List<SubCommunity> listAll(SubCommunity subCommunity)
    {
        List<SubCommunity> list = subCommunityService.selectSubCommunityList(subCommunity);
        return list;
    }

    /**
     * 查询sub_community列表
     */
    @GetMapping( "/listForApp")
    public TableDataInfo listForApp(SubCommunity subCommunity)
    {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        List<Map<String, Object>> list = subCommunityService.selectSubCommunityListForApp(user);
        return getDataTable(list);
    }



    /**
     * 根据部门信息获取行政区划信息
     * 该方法会根据部门中的行政区划代码(administrativeCode)逐级查询对应的行政区划信息
     * 行政区划代码规则：2位省级，4位市级，6位区级，8位街道，10位社区，12位小区
     *
     * @param ajax 用于返回结果的AjaxResult对象，会将查询到的行政区划信息存入其中
     * @param sysDept 部门对象，包含行政区划代码(administrativeCode)
     */
    private void getAdministrative(AjaxResult ajax, SysDept sysDept) {
        if (sysDept.getAdministrativeCode() == null) {
            return;
        }

        String code = sysDept.getAdministrativeCode();
        // 定义行政区划级别及其对应的代码长度
        String[] levels = {"provice", "city", "county", "town", "village", "community"};
        int[] codeLengths = {2, 4, 6, 8, 10, 12};
        String[] nameSuffixes = {"Name", "Name", "Name", "Name", "Name", "Name"};
        String[] listSuffixes = {null, "townList", "townList", "villageList", "communityList", null};

        for (int i = 0; i < levels.length; i++) {
            if (code.length() >= codeLengths[i]) {
                // 设置当前级别行政区划代码
                ajax.put(levels[i], code);
                // 设置当前级别行政区划名称
                String currentCode = code.substring(0, codeLengths[i]);
                SysAdministrative admin = getAdministrativeByCode(currentCode);
                ajax.put(levels[i] + nameSuffixes[i], admin);
                // 设置下级行政区划列表
                if (listSuffixes[i] != null && i < levels.length - 1) {
                    SysAdministrative query = new SysAdministrative();
                    query.setParentCode(currentCode);
                    ajax.put(listSuffixes[i], sysAdministrativeService.selectSysAdministrativeList(query));
                }
            }
        }
    }

    /**
     * 根据行政区划代码获取行政区划信息
     */
    private SysAdministrative getAdministrativeByCode(String code) {
        SysAdministrative query = new SysAdministrative();
        query.setAdministrativeCode(code);
        List<SysAdministrative> list = sysAdministrativeService.selectSysAdministrativeList(query);
        return list.isEmpty() ? null : list.get(0);
    }
    /**
     * 导出sub_community列表
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:export')")
    @Log(title = "sub_community", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SubCommunity subCommunity)
    {
        List<SubCommunity> list = subCommunityService.selectSubCommunityList(subCommunity);
        ExcelUtil<SubCommunity> util = new ExcelUtil<SubCommunity>(SubCommunity.class);
        util.exportExcel(response, list, "sub_community数据");
    }

    /**
     * 获取sub_community详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(subCommunityService.selectSubCommunityById(id));
    }

    /**
     * 新增sub_community
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:add')")
    @Log(title = "sub_community", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SubCommunity subCommunity)
    {
        subCommunity.setId( UUID.randomUUID().toString());
        return toAjax(subCommunityService.insertSubCommunity(subCommunity));
    }

    /**
     * 修改sub_community
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:edit')")
    @Log(title = "sub_community", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SubCommunity subCommunity)
    {
        return toAjax(subCommunityService.updateSubCommunity(subCommunity));
    }

    /**
     * 删除sub_community
     */
    @PreAuthorize("@ss.hasPermi('system:subCommunity:remove')")
    @Log(title = "sub_community", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(subCommunityService.deleteSubCommunityByIds(ids));
    }

    /**
     * 修改street_community
     */
    @PostMapping("/saveData")
    public AjaxResult saveData(@RequestBody  SubCommunity subCommunity)
    {
        return toAjax(subCommunityService.saveData(subCommunity));
    }
}
